﻿'Imports System.Data
Imports System
Imports System.Net
Imports System.IO

Public Class httpcalls

    Public Enum HTTPMethod As Short
        'Enumerate the HTTP_GET and HTTP_POST methods
        HTTP_GET = 0
        HTTP_POST = 1
    End Enum

    Public cookies As New CookieCollection
    Public sesskey As String

    Public Function isAuthenticated() As Boolean
        'what we need to send to the server so we can get logged in
        Dim PostData As String = ""
        Dim Method As HTTPMethod = HTTPMethod.HTTP_POST
        'calculate the length of the post data
        Dim bytArguments As Byte() = System.Text.Encoding.ASCII.GetBytes(PostData)

        'we dont have a content type defined
        Dim ContentType As String = ""

        'holds the response that the server sends back
        Dim Response As HttpWebResponse

        'a streamWriter
        Dim SW As StreamWriter

        'a streamReader
        Dim SR As StreamReader

        'holds some response data
        Dim ResponseData As String

        Dim request3 As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "auth.php")


        ' Prepare Request Object
        request3.Method = Method.ToString().Substring(5)


        ' Set form/post content-type if necessary
        If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
            ContentType = "application/x-www-form-urlencoded"
        End If

        ' Set Content-Type
        If (ContentType <> "") Then
            request3.ContentType = ContentType
            request3.ContentLength = PostData.Length
        End If

        'the moodle uses 3 cookies
        request3.CookieContainer = New CookieContainer
        request3.CookieContainer.Add(cookies)


        'once again turn off keepalive
        request3.KeepAlive = False

        ' Send Request, If Request
        If (Method = HTTPMethod.HTTP_POST) Then
            Try
                SW = New StreamWriter(request3.GetRequestStream())
                SW.Write(PostData)
                SW.Close()
            Catch Ex As Exception
                MsgBox("Somthing Bad Happened")
                Exit Function
            End Try
        End If

        ' Receive Response
        Try

            Response = request3.GetResponse()
            SR = New StreamReader(Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            SR.Close()
            Response.Close()

        Catch Wex As System.Net.WebException
            SR = New StreamReader(Wex.Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            MsgBox("Somthing Bad Happened" & ResponseData)
            Exit Function
        End Try






        If (ResponseData = "Authenticated") Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Function login(ByVal Username As String, ByVal Password As String) As Boolean
        frmSplash.Authlabel.Visible = True
        frmSplash.Refresh()

        'this subrutine logs the current user into the moodle
        'this rutine sends two requests to the server the first is just used to get the cookies required to login

        'what we need to send to the server so we can get logged in
        Dim PostData As String = "username=" & Username & "&password=" & Password & "&testcookies=1"

        'calculate the length of the post data
        Dim bytArguments As Byte() = System.Text.Encoding.ASCII.GetBytes(PostData)

        'we dont have a content type defined
        Dim ContentType As String = ""

        'holds the response that the server sends back
        Dim Response As HttpWebResponse

        'a streamWriter
        Dim SW As StreamWriter

        'a streamReader
        Dim SR As StreamReader

        'holds some response data
        Dim ResponseData As String

        frmSplash.Authlabel.Text = "Authenticating.."
        frmSplash.Refresh()

        'first request
        'will not login the user
        'needs cookies first
        'url of the home page of the moodle
        If (frmSplash.regsettings.getSvrURL.StartsWith("http://") = False) Then
            MsgBox("Error You need to put " & Chr(34) & "Http://" & Chr(34) & " before your URL")

            Exit Function


        End If


        Dim request As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "index.php")

        'were going to do a post
        Dim Method As HTTPMethod = HTTPMethod.HTTP_POST

        'need keepalive off so we dont have issues
        request.KeepAlive = False
        request.CookieContainer = New CookieContainer()


        ' Prepare Request Object
        request.Method = Method.ToString().Substring(5)

        'Set form/post content-type if necessary
        If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
            ContentType = "application/x-www-form-urlencoded"
        End If

        'Set Content-Type
        If (ContentType <> "") Then
            request.ContentType = ContentType
            request.ContentLength = bytArguments.Length
        End If

        'Send Request, If Request
        If (Method = HTTPMethod.HTTP_POST) Then
            Try
                SW = New StreamWriter(request.GetRequestStream())
                SW.Write(PostData)
                SW.Close()

            Catch Ex As Exception
                MsgBox("Error Could Not Connect, Check your URL")
                Exit Function
            End Try
        End If


        ' Receive Response
        Try
            Response = request.GetResponse()
            cookies = Response.Cookies
            SR = New StreamReader(Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            SR.Close()

            Response.Close()
        Catch Wex As System.Net.WebException
            SR = New StreamReader(Wex.Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            MsgBox("Error, Check your connection URL")
            Exit Function
        End Try

        frmSplash.Authlabel.Text = "Authenticating."
        frmSplash.Refresh()

        'now that we have the cookies
        'we can send them and get authenticated
        Dim request2 As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "login/index.php")


        ' Prepare Request Object
        request2.Method = Method.ToString().Substring(5)


        ' Set form/post content-type if necessary
        If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
            ContentType = "application/x-www-form-urlencoded"
        End If

        ' Set Content-Type
        If (ContentType <> "") Then
            request2.ContentType = ContentType
            request2.ContentLength = PostData.Length
        End If

        'the moodle uses 3 cookies
        request2.CookieContainer = New CookieContainer
        request2.CookieContainer.Add(cookies)
        'request2.CookieContainer.Add(cookies.Item(1))
        ' request2.CookieContainer.Add(cookies.Item(4))

        'add the cookies to the public variable
        'cookies.Add(cookies.Item(2))
        'cookies.Add(cookies.Item(3))
        'cookies.Add(cookies.Item(4))

        'once again turn off keepalive
        request2.KeepAlive = False

        ' Send Request, If Request
        If (Method = HTTPMethod.HTTP_POST) Then
            Try
                SW = New StreamWriter(request2.GetRequestStream())
                SW.Write(PostData)
                SW.Close()
            Catch Ex As Exception
                MsgBox("Somthing Bad Happened")
            End Try
        End If
        frmSplash.Authlabel.Text = "Authenticating"
        frmSplash.Refresh()
        ' Receive Response
        Try

            Response = request2.GetResponse()
            'cookies = Response.Cookies
            SR = New StreamReader(Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            SR.Close()
            Response.Close()

        Catch Wex As System.Net.WebException
            SR = New StreamReader(Wex.Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            MsgBox("Somthing Bad Happened" & ResponseData)
        Finally
            SR.Close()
            Response.Close()
        End Try


        frmSplash.Authlabel.Text = "Authenticating..."
        frmSplash.Refresh()
        'now that we have the cookies
        'we can send them and get authenticated
        Dim request3 As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "auth.php")


        ' Prepare Request Object
        request3.Method = Method.ToString().Substring(5)


        ' Set form/post content-type if necessary
        If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
            ContentType = "application/x-www-form-urlencoded"
        End If

        ' Set Content-Type
        If (ContentType <> "") Then
            request3.ContentType = ContentType
            request3.ContentLength = PostData.Length
        End If

        'the moodle uses 3 cookies
        request3.CookieContainer = New CookieContainer
        request3.CookieContainer.Add(cookies)
        'request3.CookieContainer.Add(cookies.Item(1))
        'request3.CookieContainer.Add(cookies.Item(4))

        'once again turn off keepalive
        request3.KeepAlive = False

        ' Send Request, If Request
        If (Method = HTTPMethod.HTTP_POST) Then
            Try
                SW = New StreamWriter(request3.GetRequestStream())
                SW.Write(PostData)
                SW.Close()
            Catch Ex As Exception
                MsgBox("Somthing Bad Happened")
            End Try
        End If
        frmSplash.Authlabel.Text = "Authenticating.."
        frmSplash.Refresh()
        ' Receive Response
        Try

            Response = request3.GetResponse()
            SR = New StreamReader(Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            SR.Close()
            Response.Close()

        Catch Wex As System.Net.WebException
            SR = New StreamReader(Wex.Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            MsgBox("Somthing Bad Happened" & ResponseData)
        End Try


        Dim Auth As String = ResponseData


        Dim request4 As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "sesskey.php")


        ' Prepare Request Object
        request4.Method = Method.ToString().Substring(5)


        ' Set form/post content-type if necessary
        If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
            ContentType = "application/x-www-form-urlencoded"
        End If

        ' Set Content-Type
        If (ContentType <> "") Then
            request4.ContentType = ContentType
            request4.ContentLength = PostData.Length
        End If

        'the moodle uses 3 cookies
        request4.CookieContainer = New CookieContainer
        request4.CookieContainer.Add(cookies)
        'request4.CookieContainer.Add(cookies.Item(1))
        'request4.CookieContainer.Add(cookies.Item(4))

        'once again turn off keepalive
        request4.KeepAlive = False

        ' Send Request, If Request
        If (Method = HTTPMethod.HTTP_POST) Then
            Try
                SW = New StreamWriter(request4.GetRequestStream())
                SW.Write(PostData)
                SW.Close()
            Catch Ex As Exception
                MsgBox("Somthing Bad Happened")
            End Try
        End If
        frmSplash.Authlabel.Text = "Authenticating.."
        frmSplash.Refresh()
        ' Receive Response
        Try

            Response = request4.GetResponse()
            SR = New StreamReader(Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            SR.Close()
            Response.Close()

        Catch Wex As System.Net.WebException
            SR = New StreamReader(Wex.Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            MsgBox("Somthing Bad Happened" & ResponseData)
        End Try



        frmSplash.Authlabel.Text = "Authenticating."
        frmSplash.Refresh()
        frmSplash.Authlabel.Visible = False

        sesskey = ResponseData.Trim(Chr(9)).Trim(Chr(32))










        If (Auth = "Authenticated") Then
            Return True
        Else
            Return False
        End If

    End Function

    Public Function getClasses() As List(Of Course)

        ProgressBarfrm.Show()
        ProgressBarfrm.Activate()
        ProgressBarfrm.Refresh()




        Dim courses As New List(Of Course)
        Dim assignments As New List(Of Assignment)




        'what we need to send to the server so we can get logged in
        Dim PostData As String = ""
        Dim Method As HTTPMethod = HTTPMethod.HTTP_POST
        'calculate the length of the post data
        Dim bytArguments As Byte() = System.Text.Encoding.ASCII.GetBytes(PostData)

        'we dont have a content type defined
        Dim ContentType As String = ""

        'holds the response that the server sends back
        Dim Response As HttpWebResponse

        'a streamWriter
        Dim SW As StreamWriter

        'a streamReader
        Dim SR As StreamReader

        'holds some response data
        Dim ResponseData As String

        Dim request3 As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "user/mycourses.php")


        ' Prepare Request Object
        request3.Method = Method.ToString().Substring(5)


        ' Set form/post content-type if necessary
        If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
            ContentType = "application/x-www-form-urlencoded"
        End If

        ' Set Content-Type
        If (ContentType <> "") Then
            request3.ContentType = ContentType
            request3.ContentLength = PostData.Length
        End If

        'the moodle uses 3 cookies
        request3.CookieContainer = New CookieContainer
        request3.CookieContainer.Add(cookies)


        'once again turn off keepalive
        request3.KeepAlive = False

        ' Send Request, If Request
        If (Method = HTTPMethod.HTTP_POST) Then
            Try
                SW = New StreamWriter(request3.GetRequestStream())
                SW.Write(PostData)
                SW.Close()
            Catch Ex As Exception
                MsgBox("Somthing Bad Happened")
            End Try
        End If

        ' Receive Response
        Try

            Response = request3.GetResponse()
            SR = New StreamReader(Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            SR.Close()
            Response.Close()

        Catch Wex As System.Net.WebException
            SR = New StreamReader(Wex.Response.GetResponseStream())
            ResponseData = SR.ReadToEnd()
            MsgBox("Somthing Bad Happened" & ResponseData)
        End Try
        Dim i = 0

        ResponseData = SandR(ResponseData, "amp;", "&")

        Dim courseData As New List(Of String)(ResponseData.Split(";"))



        i = 0
        If (courseData.Count < 2) Then
            MsgBox("Error: You are not enrolled in any courses")
            End
        End If

        While (courseData.Count > i + 1)

            Dim course As New List(Of String)(courseData.Item(i).Split("`"))

            Dim c As New Course(course.Item(2), course.Item(0))
            'MsgBox(course.Item(2) & course.Item(0))
            courses.Add(c)

            i += 1
        End While
        'Return courses
        i = 0
        Dim f = 0
        While (courses.Count > i)
            ProgressBarfrm.ProgressBar1.Increment(Int(ProgressBarfrm.ProgressBar1.Maximum / courses.Count))
            ProgressBarfrm.Refresh()


            Dim request As HttpWebRequest = WebRequest.Create(frmSplash.regsettings.getSvrURL & "/mod/assignment/listassignments.php?id=" & courses.Item(i).getid())


            ' Prepare Request Object
            request.Method = Method.ToString().Substring(5)


            ' Set form/post content-type if necessary
            If (Method = HTTPMethod.HTTP_POST AndAlso PostData <> "" AndAlso ContentType = "") Then
                ContentType = "application/x-www-form-urlencoded"
            End If

            ' Set Content-Type
            If (ContentType <> "") Then
                request.ContentType = ContentType
                request.ContentLength = PostData.Length
            End If

            'the moodle uses 3 cookies
            request.CookieContainer = New CookieContainer
            request.CookieContainer.Add(cookies)

            'once again turn off keepalive
            request.KeepAlive = False

            ' Send Request, If Request
            If (Method = HTTPMethod.HTTP_POST) Then
                Try
                    SW = New StreamWriter(request.GetRequestStream())
                    SW.Write(PostData)
                    SW.Close()
                Catch Ex As Exception
                    MsgBox("Somthisdfsdfng Bad Happened")
                End Try
            End If

            ' Receive Response
            Try

                Response = request.GetResponse()
                SR = New StreamReader(Response.GetResponseStream())
                ResponseData = SR.ReadToEnd()
                SR.Close()
                Response.Close()

            Catch Wex As System.Net.WebException
                SR = New StreamReader(Wex.Response.GetResponseStream())
                ResponseData = SR.ReadToEnd()
                MsgBox("Somthing Bad Happened" & ResponseData)
            End Try

            Dim assignmentData As New List(Of String)(ResponseData.Split("`"))

            f = 0
            While (assignmentData.Count > f + 1)

                Dim assignment As New List(Of String)(assignmentData.Item(f).Split(","))

                courses.Item(i).addassignments(assignment.Item(1), assignment.Item(0))
                'MsgBox(assignment.Item(1) & Chr(13) & Chr(10) & assignment.Item(0) & Chr(13) & Chr(10) & courses.Item(i).getid())
                'assignments.Add(a)


                'MsgBox(courses.Item(i).getassignmentlist.Item(0).getassignmentname)
                f += 1
                assignment.Clear()

            End While
            'courses.Item(i).setassignmentlist(assignments)
            'MsgBox(courses.Item(i).getassignmentlist.Item(0).getassignmentname)
            assignments.Clear()
            i += 1
            assignmentData.Clear()
        End While
        ProgressBarfrm.ProgressBar1.Value = ProgressBarfrm.ProgressBar1.Maximum
        ProgressBarfrm.Hide()
        ProgressBarfrm.ProgressBar1.Value = ProgressBarfrm.ProgressBar1.Minimum
        Return courses
    End Function

    Function SandR(ByVal SearchString As String, ByVal LookFor As String, ByVal ReplaceWith As String) As String
        REM +-----------------------------------------------------------------------+
        REM |    SearchString    =   String to search.                              |
        REM |    LookFor         =   String to look for within SearchString         |
        REM |    ReplaceWith     =   What to replace SearchString                   |
        REM |                                                                       |
        REM |    Test=SandR("Mary Had a little lamb","a","aa")                      |
        REM |                would return:                                          |
        REM |            Maary Haad aa little laamb                                 |
        REM |                                                                       |
        REM |   Compatibility: Visual Basic 2.0                                     |
        REM |                                                                       |
        REM |       Programmed by: JamesTracy95820@hotmail.com                      |
        REM |                                                                       |
        REM +-----------------------------------------------------------------------+
        REM +-----------------------------------+
        REM |       Declair variables           |
        REM +-----------------------------------+
        Dim LeftPart As String
        Dim RightPart As String
        Dim Location As Integer
        Dim LeftLocation As Integer
        Dim RightLocation As Integer
        REM +-------------------------------+
        REM |       Initilize variables     |
        REM +-------------------------------+
        LeftPart = ""
        RightPart = ""
        Location = 0
        REM ==========================================================
        If Len(LookFor) = 0 Then
            LeftPart = SearchString
        Else
            If LookFor = ReplaceWith Then
                LeftPart = SearchString
            Else
                If Len(SearchString) = 0 Then
                    LeftPart = SearchString
                Else
                    LeftPart = ""
                    RightPart = SearchString
                    REM ============================================
                    Do
                        Location = InStr(1, RightPart, LookFor, 0)  '   Case INsensitive
                        If Location = 0 Then
                            LeftPart = LeftPart + RightPart
                        Else
                            If Location = 1 Then
                                LeftPart = LeftPart + ReplaceWith
                                RightLocation = Location + Len(LookFor)
                                If RightLocation > Len(RightPart) Then
                                    RightPart = ""
                                Else
                                    RightPart = Mid(RightPart, RightLocation)
                                End If
                            Else
                                If Location >= 2 Then
                                    LeftLocation = Location - 1
                                    RightLocation = Location + Len(LookFor)
                                    LeftPart = LeftPart + Left(RightPart, LeftLocation) + ReplaceWith
                                    If RightLocation > Len(RightPart) Then
                                        RightPart = ""
                                    Else
                                        RightPart = Mid(RightPart, RightLocation)
                                    End If
                                End If
                            End If
                        End If
                    Loop Until Location = 0
                End If
            End If
        End If
        SandR = LeftPart   '   Return string
    End Function



End Class
